package org.jeecg.modules.syncdata.handler;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.util.ShardingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.syncdata.dto.SyncDataDto;
import org.jeecg.modules.syncdata.service.SyncResultService;
import org.jeecg.modules.syncdata.service.SyncService;
import org.jeecg.modules.syncdata.vo.SyncResultVo;
import org.jeecg.modules.thirdpartyapi.constant.BgApiEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.xxl.job.core.biz.model.ReturnT.FAIL;
import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;

/**
 * 同步处理程序
 *
 * @author zhanglei01
 * @date 2022/03/16
 */
@Slf4j
@Component
public class SyncBgHandler {

    @Value("${xxl.job.executor.ip}")
    private String ip;

    @Autowired
    private SyncService syncService;

    @Autowired
    private SyncResultService syncResultService;


    @XxlJob(value = "syncBgHandler")
    public ReturnT<String> execute(String jobParam) throws Exception {
        //处理请求参数
        SyncDataDto syncDataDto = null;
        if (StringUtils.isNotBlank(jobParam)) {
            syncDataDto = JSONObject.parseObject(jobParam, SyncDataDto.class);
        } else {
            return FAIL;
        }
        //如果所有的参数都是空的，先判断下全部数据是否同步完成
        if (StrUtil.isAllBlank(syncDataDto.getStartTime(), syncDataDto.getEndTime(), syncDataDto.getTableName())) {
            Boolean allFinish = syncResultService.isAllFinish();
            if (allFinish) {
                log.info("没有需要同步的数据，全部数据同步已完成！");
                return SUCCESS;
            }
        }
        //如果入参有设置表名，只同步设置的表，没有设置就同步BgApiEnum中的所有表数据
        BgApiEnum[] values = null;
        if (StringUtils.isNotBlank(syncDataDto.getTableName())) {
            for (BgApiEnum value : BgApiEnum.values()) {
                if (value.getValue().equals(syncDataDto.getTableName())) {
                    values = new BgApiEnum[1];
                    values[0] = value;
                    break;
                }
            }
        }
        //没有设置就同步BgApiEnum中的所有表数据
        if (values == null || values.length == 0) {
            values = BgApiEnum.values();
            syncDataDto.setTableName("");
        }

        //获取分片信息
        ShardingUtil.ShardingVO shardingVo = ShardingUtil.getShardingVo();
        if (shardingVo == null) {
            shardingVo = new ShardingUtil.ShardingVO(0, 1);
        }
        log.info("SyncHandler同步数据,分片参数：当前分片序号 = {}, 总分片数 = {},ip={}", shardingVo.getIndex(), shardingVo.getTotal(), ip);

        ExecutorService executor = new ThreadPoolExecutor(5, 5, 0L,
                TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        //获取同步结束日期
        DateTime syncEndTime = DateUtil.beginOfDay(DateUtil.yesterday());
        if (StringUtils.isNotBlank(syncDataDto.getEndTime())) {
            DateTime endTime = DateUtil.parseDate(syncDataDto.getEndTime());
            if (endTime.isBefore(syncEndTime)) {
                syncEndTime = endTime;
            }
        }
        //遍历待同步的表
        for (BgApiEnum bgApiEnum : values) {
            //分片，只同步命中的
            if (bgApiEnum.getSort() % shardingVo.getTotal() != shardingVo.getIndex()) {
                continue;
            }
            log.info("syncBgHandler同步：{}表数据,第 {} 片, 命中分片开始处理", bgApiEnum.getValue(), shardingVo.getIndex());
            //获取本次同步时间区间
            String nextTime = syncResultService.getNextTime(bgApiEnum.getValue(), syncDataDto.getStartTime());
            //判断是否需要同步，如果nextTime时间是今天或者之后，本次不在同步。
            DateTime syncTime = DateUtil.parseDate(nextTime);
            if (syncTime.isAfter(syncEndTime)) {
                log.info("syncBgHandler同步：{}表数据无需同步", bgApiEnum.getValue());
                continue;
            }
            List<DateTime> dateTimes = DateUtil.rangeToList(syncTime, syncEndTime, DateField.DAY_OF_YEAR);
            SyncResultVo syncResultVo = new SyncResultVo();
            String createNextTime = DateUtil.offsetDay(syncEndTime, 1).toDateStr();
            //遍历同步时间区间
            for (DateTime dateTime : dateTimes) {
                if (bgApiEnum.equals(BgApiEnum.swzbjc_order) || bgApiEnum.equals(BgApiEnum.sjmkjg_order)) {
                    //判断当日其他表是否同步完成
                    String dateTimeStr = dateTime.toDateStr();
                    Boolean syncResultExceptOrder = syncResultService.getSyncResultExceptOrder(dateTimeStr);
                    if (!syncResultExceptOrder) {
                        createNextTime = dateTimeStr;
                        syncResultVo.setMsg("存在其他表未同步");
                        break;
                    }
                }
                try {
                    syncResultVo = syncService.syncSingleTable(executor, bgApiEnum, dateTime);
                } catch (Exception e) {
                    log.error("syncBgHandler同步：{}表数据异常", bgApiEnum.getValue(), e);
                    syncResultVo.setIsSuccess(false);
                    syncResultVo.setMsg(StringUtils.substring(e.getMessage(), 0, 500));
                }
                if (!syncResultVo.getIsSuccess()) {
                    createNextTime = dateTime.toDateStr();
                    break;
                }
            }
            syncResultService.setNextTime(bgApiEnum.getValue(), createNextTime, StringUtils.substring(syncResultVo.getMsg(), 0, 500));
        }
        executor.shutdown();
        log.info("同步数据执行完成");
        return SUCCESS;
    }

}
